//================v1要点总结===============
/**
 * 1.对v1进行稍微简化
 * 
 */


/**
 * @param {number[][]} grid
 * @return {number}
 */
var orangesRotting = function (grid) {
    let r = grid.length
    let c = grid[0].length
    let tempArr = new Array(r)

    // 方向
    let dir = [[-1, 0], [0, 1], [1, 0], [0, -1]]
    // 用于记录新鲜橘子的个数
    let restCount = r * c

    let queue = []
    for (let i = 0; i < r; i++) {
        let tempCArr = new Array(c)
        for (let j = 0; j < c; j++) {
            // 复制一份，避免影响输入
            tempCArr[j] = grid[i][j]

            if (tempCArr[j] !== 1) {
                // 排除空白和坏橘子
                restCount--
            }
            // 找到烂橘子，加入队列
            if (tempCArr[j] === 2) {
                queue.push([i, j])
            }
        }
        tempArr[i] = tempCArr
    }

    // 开始广度优先遍历
    let rslt = 0
    while (queue.length) {
        let temp = queue.shift()
        let [x, y] = temp
        let lastVal = tempArr[x][y]
        for (let i = 0; i < dir.length; i++) {
            let tempR = x + dir[i][0]
            let tempC = y + dir[i][1]
            if (tempR >= 0 && tempR < r && tempC >= 0 && tempC < c && tempArr[tempR][tempC] === 1) {
                // 从各烂橘子开始便遍历的，一定是最短路径
                tempArr[tempR][tempC] = lastVal + 1
                rslt = tempArr[tempR][tempC] - 2
                queue.push([tempR, tempC])
                restCount--
            }
        }
    }
    return restCount > 0 ? -1 : rslt
};

// console.log(orangesRotting([[2, 1, 1], [1, 1, 0], [0, 1, 1]]))
// console.log(orangesRotting([
//     [2],
//     [0],
//     [1]]))
console.log(orangesRotting([
    [2, 0, 1, 1, 1, 1, 1, 1, 1, 1],
    [1, 0, 1, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 1, 0, 1, 1, 1, 1, 0, 1],
    [1, 0, 1, 0, 1, 0, 0, 1, 0, 1],
    [1, 0, 1, 0, 1, 0, 0, 1, 0, 1],
    [1, 0, 1, 0, 1, 1, 0, 2, 0, 1],
    [1, 0, 1, 0, 0, 0, 0, 1, 0, 1],
    [1, 0, 1, 1, 1, 1, 1, 1, 0, 1],
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]))